package com.tanhua.manager.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tanhua.manager.constant.CacheKey;
import com.tanhua.manager.domain.Admin;
import com.tanhua.manager.exception.BusinessException;
import com.tanhua.manager.interceptor.AdminHolder;
import com.tanhua.manager.mapper.AdminMapper;
import com.tanhua.manager.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;


@Slf4j
@Service
public class AdminService {
    @Value("{tanhua.secret}")
    private String secret;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private AdminMapper adminMapper;
    /**
     * 将验证码的值缓存到redis中
     * @param code  验证码
     * @param uuid  浏览器随机生成的字符串 存储验证码时的key
     */
    public void cacheCode(String code, String uuid) {
        redisTemplate.opsForValue().set(CacheKey.CODE_PREFIX + uuid, code, Duration.ofMinutes(5));
    }

    /**
     * 校验验证码登录
     * @param username 用户名
     * @param password  密码
     * @param verificationCode  验证码
     * @param uuid  浏览器生成随机字符串
     * @return token
     */
    public ResponseEntity login(String username, String password, String verificationCode, String uuid) {
        //1. 校验验证码
        String code = redisTemplate.opsForValue().get(CacheKey.CODE_PREFIX + uuid);
        if (code == null || !code.equals(verificationCode)) {
            throw new BusinessException("验证码错误");
        }
        redisTemplate.delete(CacheKey.CODE_PREFIX + uuid);
        //2. 根据用户名查询admin
        LambdaQueryWrapper<Admin> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Admin::getUsername,username);
        Admin admin = adminMapper.selectOne(wrapper);
        if (admin == null) {
            throw new BusinessException("用户名不存在");
        }
        //3. 校验密码
        if (password == null || !DigestUtils.md5Hex(password).equals(admin.getPassword())) {
            throw new BusinessException("密码错误");
        }
        //4. 生成token
        String token = JwtUtils.createToken(admin, secret);
        redisTemplate.opsForValue().set(CacheKey.TOKEN_PREFIX + admin.getId(), token);

        //6. 构造返回值
        Map<String, Object> result = new HashMap<>();
        result.put("token", token);
        return ResponseEntity.ok(result);
    }

    /**
     * 获取用户基本信息
     * @return
     */
    public ResponseEntity profile() {
        Admin admin = AdminHolder.getAdmin();
        Map<String, Object> result = new HashMap<>();
        result.put("id", admin.getId());
        result.put("username", admin.getUsername());
        result.put("avatar", admin.getAvatar());
        return ResponseEntity.ok(result);
    }

    /**
     * 退出登录
     */
    public ResponseEntity logout() {
        Admin admin = AdminHolder.getAdmin();
        redisTemplate.delete(CacheKey.TOKEN_PREFIX + admin.getId());
        return ResponseEntity.ok(null);
    }
}
